import { defineStore } from "pinia";

export const useCartStore = defineStore("cart", {
  state: () => ({
    // 购物车商品列表
    items: [],
  }),

  actions: {
    /* ========== 购物车商品相关方法 ========== */
    addToCart(product, selectedSpecs = {}, quantity = 1) {
      const existingItem = this.items.find(
        (item) =>
          item.id === product.id &&
          JSON.stringify(item.selectedSpecs) === JSON.stringify(selectedSpecs)
      );
      if (existingItem) {
        existingItem.quantity += quantity;
      } else {
        this.items.push({
          ...product,
          selectedSpecs,
          quantity,
          checked: true,
        });
      }
      this.saveCartItems();
    },

    toggleAll(checked) {
      this.items.forEach((item) => {
        item.checked = checked;
      });
      this.saveCartItems();
    },

    toggleCheck(index) {
      if (index >= 0 && index < this.items.length) {
        this.items[index].checked = !this.items[index].checked;
        this.saveCartItems();
      }
    },

    removeItem(index) {
      if (index >= 0 && index < this.items.length) {
        this.items.splice(index, 1);
        this.saveCartItems();
      }
    },

    // 清空购物车
    clearCart() {
      this.items = [];
      this.saveCartItems();
    },

    updateQuantity(index, newQuantity) {
      if (index >= 0 && index < this.items.length) {
        this.items[index].quantity = newQuantity;
        this.saveCartItems();
      }
    },

    // 清除已选中的商品
    clearCheckedItems() {
      this.items = this.items.filter((item) => !item.checked);
      this.saveCartItems();
    },

    /* ========== 数据持久化方法 ========== */
    
    // 保存购物车数据
    saveCartItems() {
      localStorage.setItem('cartItems', JSON.stringify(this.items));
    },

    // 从本地存储初始化数据
    initializeFromLocalStorage() {
      this.items = JSON.parse(localStorage.getItem('cartItems')) || [];
    }
  },

  getters: {
    /* ========== 购物车计算属性 ========== */
    itemTotal: (state) => (index) => {
      const item = state.items[index];
      return item ? item.retailPrice * item.quantity : 0;
    },

    // 计算购物车商品总数量
    totalQuantity: (state) =>
      state.items.reduce((total, item) => total + item.quantity, 0),

    // 计算购物车选中商品总价
    totalPrice: (state) =>
      state.items.reduce((total, item) => {
        return total + (item.checked ? item.retailPrice * item.quantity : 0);
      }, 0),

    // 获取选中的商品列表
    checkedItems: (state) => state.items.filter(item => item.checked),

    // 检查是否全选
    isAllChecked: (state) => {
      if (state.items.length === 0) return false;
      return state.items.every(item => item.checked);
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: "cart",
        storage: localStorage,
        paths: ['items'] 
      }
    ]
  }
});